package org.example.Server.utils;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.example.Server.controller.RetryInterceptor;
import org.example.Server.mapper.unit.UnitMapper;
import org.example.Server.model.BaiduAgentRequest;
import org.example.Server.model.unit.UnitVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class SreamUtils {
    // 获取摘要
    final String appIntroId = "noNngin56c1mVn54hOnoT3BpYah7QY9I";
    final String secretIntroKey = "wsLXFFLfuvseYEUPiLJLPz7Z2TXeb3pJ";
    @Autowired
    UnitMapper unitMapper;
    private final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .addInterceptor(new RetryInterceptor(5, 1000)) // 最多重试3次，每次间隔1秒
            .build();

    public String getIntro(Integer semId, Integer user_id) {
        String userId = String.valueOf(user_id);
        Gson gson = new Gson();
        List<UnitVO> data = unitMapper.getUnitsBySemId(semId);
        log.info("UnitVO:{}", data);
        String json = gson.toJson(data);
        log.info(json);

        try {
            String url = "https://agentapi.baidu.com/assistant/getAnswer?appId=" + appIntroId + "&secretKey=" + secretIntroKey;

            BaiduAgentRequest request = BaiduAgentRequest.setBaiduAgentRequest(json, userId);
            request.setSource(appIntroId);
            String requestJson = JSON.toJSONString(request);

            // 修正后的RequestBody创建方式
            okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json; charset=utf-8");
            okhttp3.RequestBody body = okhttp3.RequestBody.create(
                    requestJson,
                    mediaType
            );

            Request httpRequest = new Request.Builder()
                    .url(url)
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .build();

            // 定义重试配置
            int maxRetries = 3;
            int retryDelayMillis = 1000; // 每次重试间隔1秒
            String res = "";
            for (int attempt = 1; attempt <= maxRetries; attempt++) {
                try (Response response = client.newCall(httpRequest).execute()) {
                    if (!response.isSuccessful()) {
                        log.error("请求失败，状态码: {}, 尝试次数: {}", response.code(), attempt);
                        if (attempt == maxRetries) {
                            return null;
                        }
                    } else {
                        res = response.body().string();
                        log.info("响应内容: {}", res);

                        // 解析JSON并检查data是否为空
                        ObjectMapper mapper = new ObjectMapper();
                        JsonNode rootNode = mapper.readTree(res);

                        // 检查status是否为0且data是否为空
                        if (rootNode.path("status").asInt() == 0 && rootNode.path("data").isNull()) {
                            log.warn("获取到空数据，尝试重试 ({} of {})", attempt, maxRetries);
                            if (attempt == maxRetries) {
                                return null;
                            }
                        } else {
                            // 数据正常，继续处理
                            break;
                        }
                    }
                } catch (Exception e) {
                    log.error("请求异常，尝试次数: {}，错误: {}", attempt, e.getMessage());
                    if (attempt == maxRetries) {
                        return null;
                    }
                }

                // 等待指定时间后重试
                Thread.sleep((long) retryDelayMillis * attempt); // 指数退避策略，每次重试间隔递增
            }

            ObjectMapper mapper = new ObjectMapper();
            JsonNode rootNode = mapper.readTree(res);

            String aiResponse = "";
            try {
                aiResponse = rootNode
                        .path("data")
                        .path("content")
                        .get(0)
                        .path("data")
                        .asText();
            } catch (Exception e) {
                throw new Exception();
            }

            String rep = aiResponse.replace("```json", "").replace("```", "").trim();
            return rep;

        } catch (Exception e) {
            log.error("请求发生异常", e);
        }
        return null;
    }
}
